package com.wanpinghui.supplier.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.support.v4.util.LruCache;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.yunshl.yunshllibrary.utils.DevicesUtil;
import com.yunshl.yunshllibrary.utils.LogUtils;

import java.io.File;

/**
 * Created by xiongning on 17-12-10.
 */

public class BitmapUtilManager {

    private static BitmapUtilManager instance;

    private BitmapUtilManager() {
        init();
    }

    public static BitmapUtilManager getInstance() {
        if (instance == null) {
            instance = new BitmapUtilManager();
        }
        return instance;
    }

    private LruCache<String, Bitmap> mMemoryCache;

    public void init() {
        // 获取到可用内存的最大值，使用内存超出这个值会引起OutOfMemory异常。
        // LruCache通过构造函数传入缓存值，以KB为单位。
        if (mMemoryCache == null) {
            int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
            // 使用最大可用内存值的1/8作为缓存的大小。
            int cacheSize = maxMemory / 8;
            mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    // 重写此方法来衡量每张图片的大小，默认返回图片数量。
                    return bitmap.getByteCount() / 1024;
                }
            };
        }
    }

    public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    public Bitmap getBitmapFromMemCache(String key) {
        return mMemoryCache.get(key);
    }

    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // 源图片的高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            // 计算出实际宽高和目标宽高的比率
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // 选择宽和高中最小的比率作为inSampleSize的值，这样可以保证最终图片的宽和高
            // 一定都会大于等于目标的宽和高。
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }


    public void loadImage(final Context context, final ImageView imageView, final String url, final int maxWith, final RelativeLayout rl) {
        Glide.with(context).load(url).downloadOnly(new SimpleTarget<File>() {

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                super.onLoadFailed(e, errorDrawable);
                e.printStackTrace();
            }

            @Override
            public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
                // 创建实例
                try {
                    String path = resource.getAbsolutePath();
                    final BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(path, options);
                    int imageWidth = options.outWidth;
                    int imageHeight = options.outHeight;
                    Bitmap bitmap = BitmapUtilManager.getInstance().getBitmapFromMemCache(url);
                    // 调用上面定义的方法计算inSampleSize值
                    int reqWidth = (int) DevicesUtil.dip2px(context, maxWith);
                    int reqHeight = (int) ((reqWidth / (float) imageWidth) * imageHeight);
                    if (bitmap == null) {
                        // 调用上面定义的方法计算inSampleSize值
                        options.inSampleSize = BitmapUtilManager.getInstance().calculateInSampleSize(options, reqWidth, reqHeight);
                        // 使用获取到的inSampleSize值再次解析图片
                        options.inJustDecodeBounds = false;
                        bitmap = BitmapFactory.decodeFile(path, options);
                        BitmapUtilManager.getInstance().addBitmapToMemoryCache(url, bitmap);
                    }
                    imageView.setImageBitmap(bitmap);
                    ViewGroup.LayoutParams params = imageView.getLayoutParams();
                    params.width = reqWidth;
                    params.height = reqHeight;
                    imageView.setLayoutParams(params);
                    ViewGroup.LayoutParams params1 = rl.getLayoutParams();
                    params1.width = reqWidth;
                    params1.height = reqHeight;
                    rl.setLayoutParams(params1);
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtils.e("-----", e.getMessage());
                    //ToastManager.getInstance().showToast("内存不足,部分详情未能显示");

                    return;
                }
            }
        });
    }
}